home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c-part1 / 9828 < prev    next >
Encoding:
Text File  |  1996-08-05  |  1.8 KB  |  72 lines

  1. Path: garden.csc.calpoly.edu!not-for-mail
  2. From: dstubbs@garden.csc.calpoly.edu (Dan Stubbs)
  3. Newsgroups: comp.lang.c
  4. Subject: Re: Getting Random Numbers
  5. Date: 13 Mar 1996 11:26:58 -0800
  6. Organization: Cal Poly, San Luis Obispo
  7. Message-ID: <4i77i2$78g@garden.csc.calpoly.edu>
  8. References: <4i4k40$qa6@news.ysu.edu>
  9. NNTP-Posting-User: dstubbs@garden.csc.calpoly.edu
  10.  
  11. In article <4i4k40$qa6@news.ysu.edu>, Bryan Kelly <bp515@yfn.ysu.edu> wrote:
  12. >
  13. >I am relitivly new to programming in C.  I have a program that need to get random numbers.  Does anyone know how to do this.  I alread tried the rand() function.  Please E-Mail me at BillsFan10@aol.com  if you know.  Thanx.
  14. >-- 
  15. >Bryan "BillsFan" Kelly
  16.  
  17. Why not use rand? In case you had trouble using it, here are some examples:
  18.  
  19. In this first example the same "default" sequence of random numbers is
  20. generated every time.
  21.  
  22. #include <stdio.h>
  23. #include <stdlib.h>
  24.  
  25. int main () {
  26.    int k, rr;
  27.    for (k=1; k<=10; k++) {
  28.       rr = rand();
  29.       printf("   %6d\n", rr);
  30.    }
  31.    return 0;
  32. }
  33.  
  34. In the second example srand is used to initialize rand. The same sequence
  35. of random numbers is generated each time, but it is a different sequence
  36. than the default sequence (unless the parameter to srand is 1).
  37.  
  38. #include <stdio.h>
  39. #include <stdlib.h>
  40.  
  41. int main () {
  42.    int k, rr;
  43.    srand(777);
  44.  
  45.    for (k=1; k<=10; k++) {
  46.       rr = rand();
  47.       printf("   %6d\n", rr);
  48.    }
  49.    return 0;
  50. }
  51.  
  52. Finally, time is used to get a value to initialize rand so that a
  53. different sequence is generated each time the program is run.
  54.  
  55. #include <stdio.h>
  56. #include <stdlib.h>
  57. #include <time.h>
  58.  
  59. int main () {
  60.    int k, rr;
  61.    srand(time(NULL));
  62.  
  63.    for (k=1; k<=10; k++) {
  64.       rr = rand();
  65.       printf("   %6d\n", rr);
  66.    }
  67.    return 0;
  68. }
  69.  
  70. There is further information about random numbers in the FAQ for
  71. this group.
  72.